package com.my.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class CryptoUtil {

  private static final String DEFAULT_CHARSET = "UTF-8";

  public static String SHA256(String str){

    MessageDigest messageDigest;

    String encodeStr ="";
    // MessageDigest md = MessageDigest.getInstance("SHA-256");
    try {
      messageDigest= MessageDigest.getInstance("SHA-256");
      messageDigest.update(str.getBytes("UTF-8"));
      byte[] digest = messageDigest.digest();
      encodeStr= byte2Hex(digest);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return encodeStr;
  }

  //二行制转字符串
  public static String byte2Hex(byte[] b) {
    String hs="";
    String stmp="";
    for (int n=0;n<b.length;n++) {
      stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
      if (stmp.length()==1) hs=hs+"0"+stmp;
      else hs=hs+stmp;
      //if (n<b.length-1)  hs=hs+":";
    }
    //return hs.toUpperCase();
    return hs.toLowerCase();
  }

  /**
   * MD5加密，默认UTF-8
   *
   * @param str a {@link java.lang.String} object.
   * @return a {@link java.lang.String} object.
   */
  public static String MD5(final String str) {
    return encodeMD5(str, DEFAULT_CHARSET);
  }

  /**
   * MD5加密
   * @param str     a {@link java.lang.String} object.
   * @param charset a {@link java.lang.String} object.
   * @return a {@link java.lang.String} object.
   */
  public static String encodeMD5(final String str, final String charset) {
    if (str == null) {
      return null;
    }
    try {
      byte[] bytes = str.getBytes(charset);
      return encodeMD5(bytes);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * MD5加密
   *
   * @param bytes an array of byte.
   * @return a {@link java.lang.String} object.
   */
  public static String encodeMD5(final byte[] bytes) {
    return DigestUtils.md5Hex(bytes);
  }

  public static String uuid(){
    //String s = UUID.randomUUID().toString().replaceAll("-", "");
    String s = UUID.randomUUID().toString().replace("-", "");
    return s;
  }

  public static void main(String[] args) {
    String uuid = CryptoUtil.uuid();
    System.out.println(uuid);
  }
}
